package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.isunland.managesystem.R;
import com.isunland.managesystem.adapter.PlanManageListAdapter;
import com.isunland.managesystem.base.Base;
import com.isunland.managesystem.base.BaseListFragment;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.CurrentUser;
import com.isunland.managesystem.entity.ExtraValueContent;
import com.isunland.managesystem.entity.PlanManage;
import com.isunland.managesystem.entity.PlanManageNumber;
import com.isunland.managesystem.entity.PlanManageNumberOriginal;
import com.isunland.managesystem.entity.PlanManageOriginal;
import com.isunland.managesystem.utils.MyDateUtil;
import com.isunland.managesystem.utils.ParamsNotEmpty;
import com.isunland.managesystem.utils.ToastUtil;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import org.json.JSONException;

/**
 * 对象功能:
 * 开发公司: 北京信普达系统工程有限公司
 * 开发人员: HuXiaoDan
 * 创建时间: 2017/4/19 14:30
 */
public class PlanManageListFragment extends BaseListFragment implements View.OnClickListener {

  private final int REQUEST_ADD = 0;
  private final int REQUEST_QUERY = 1;
  private ArrayList<PlanManage> mList;
  private int mPage;
  private PlanManageListAdapter mAdapter;
  private String beginplanStartTime;
  private String endplanStartTime;
  private String excjobnoStr;
  private String excnameStr;
  private String corjobnoStr;
  private String cornameStr;
  private CurrentUser mUser;
  private TextView tvStaffInfoCount;
  private TextView tvTipLog;
  private TextView tvRegInfoCount;

  @Override public void onStart() {
    super.onStart();
    //获取提示数量个数
    volleyPostNumber();
  }

  private void volleyPostNumber() {
    final String numUrl = ApiConst.getAbsoluteUrl(ApiConst.URL_PLAN_MANAGE_NUMBER);
    ParamsNotEmpty params = new ParamsNotEmpty();
    params.put("memberCode", mUser.getMemberCode());
    params.put("userJobNo", mUser.getJobNumber());
    mActivity.volleyPost(numUrl, params.getParams(), new VolleyResponse() {
      @Override public void onVolleyError(VolleyError arg0) {

      }

      @Override public void onVolleyResponse(String arg0) throws JSONException {

        PlanManageNumberOriginal original =
            new Gson().fromJson(arg0, PlanManageNumberOriginal.class);
        if (original != null && Base.SUCCESS == original.getResult()) {
          PlanManageNumber number = original.getRows();
          tvRegInfoCount.setText(number.getRegInfoCount());
          tvStaffInfoCount.setText(number.getStaffInfoCount());
          tvTipLog.setText(number.getTipLog());

          tvRegInfoCount.setVisibility(
              !TextUtils.isEmpty(number.getRegInfoCount()) && !"0".equalsIgnoreCase(
                  number.getRegInfoCount()) ? View.VISIBLE : View.GONE);
          tvStaffInfoCount.setVisibility(
              !TextUtils.isEmpty(number.getStaffInfoCount()) && !"0".equalsIgnoreCase(
                  number.getStaffInfoCount()) ? View.VISIBLE : View.GONE);
          tvTipLog.setVisibility(
              !TextUtils.isEmpty(number.getTipLog()) && !"0".equalsIgnoreCase(number.getTipLog())
                  ? View.VISIBLE : View.GONE);

        }
      }
    });
  }

  @Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setBack(true);
    setTitleCustom(R.string.planList);
    mUser = CurrentUser.newInstance(getActivity());
    beginplanStartTime = MyDateUtil.format(MyDateUtil.getBeforeMonth(3), MyDateUtil.TYPE_DATE);
    endplanStartTime = MyDateUtil.format(new Date(), MyDateUtil.TYPE_DATE);
    excjobnoStr = mUser.getJobNumber();
    excnameStr = mUser.getRealName();
    corjobnoStr = mUser.getJobNumber();
    cornameStr = mUser.getRealName();
    mList = new ArrayList<>();
    mPage = 1;
  }

  @Override public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    View header =
        getLayoutInflater(savedInstanceState).inflate(R.layout.header_plan_manage, mListview,
            false);
    LinearLayout llToMy = (LinearLayout) header.findViewById(R.id.ll_myMessage);
    LinearLayout llFromMy = (LinearLayout) header.findViewById(R.id.ll_myPlan);
    LinearLayout llMyReminder = (LinearLayout) header.findViewById(R.id.ll_myReminder);
    tvRegInfoCount = (TextView) header.findViewById(R.id.tv_regInfoCount);
    tvStaffInfoCount = (TextView) header.findViewById(R.id.tv_staffInfoCount);
    tvTipLog = (TextView) header.findViewById(R.id.tv_tipLog);
    llToMy.setOnClickListener(this);
    llFromMy.setOnClickListener(this);
    llMyReminder.setOnClickListener(this);
    mListview.addHeaderView(header);
    mPullRefreshListView.setMode(PullToRefreshBase.Mode.BOTH);
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    super.onCreateOptionsMenu(menu, inflater);
    inflater.inflate(R.menu.menu_add_search, menu);
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case android.R.id.home:
        getActivity().finish();
        return true;
      case R.id.menu_item_add:
        //添加
        Intent add = new Intent(getActivity(), PlanManageAddActivity.class);
        startActivityForResult(add, REQUEST_ADD);
        return true;
      case R.id.menu_item_querys:
        //查询
        ExtraValueContent content = new ExtraValueContent();
        content.setExtName1(beginplanStartTime);
        content.setExtName2(endplanStartTime);
        content.setExtName3(excnameStr);
        content.setExtCode3(excjobnoStr);
        content.setExtName4(cornameStr);
        content.setExtCode4(corjobnoStr);
        Intent query = new Intent(getActivity(), PlanManageQueryActivity.class);
        query.putExtra(PlanManageQueryFragment.EXTRA_CONTENT, content);
        startActivityForResult(query, REQUEST_QUERY);
        return true;
      default:
        return super.onOptionsItemSelected(item);
    }
  }

  @Override public String getUrl() {
    return ApiConst.URL_PLAN_MANAGE_LIST;
  }

  @Override public HashMap<String, String> getparameters() {
    ParamsNotEmpty params = new ParamsNotEmpty();
    params.put("memberCode", mUser.getMemberCode());
    params.put("beginplanStartTime", beginplanStartTime);
    params.put("endplanStartTime", endplanStartTime);
    params.put("excjobnoStr", excjobnoStr);
    params.put("corjobnoStr", corjobnoStr);
    params.put("page", mPage + "");
    params.put("pageSize", "20");
    return params.getParams();
  }

  @Override public void resolveResponse(String json) {
    PlanManageOriginal original = new Gson().fromJson(json, PlanManageOriginal.class);
    ArrayList<PlanManage> rows = original.getRows();
    if (Base.SUCCESS == original.getResult() && rows != null) {
      if (rows.size() == 0) {
        ToastUtil.show(R.string.that_is_all);
      }
      if (mPage == 1) {
        mList.clear();
      }
      mList.addAll(rows);
      if (mAdapter == null) {
        mAdapter = new PlanManageListAdapter(getActivity(), mList);
        setListAdapter(mAdapter);
        return;
      }
      mAdapter.notifyDataSetChanged();
    } else {
      ToastUtil.show("获取列表失败");
    }
  }

  @Override public void onListItemClick(ListView l, View v, int position, long id) {
    //避免点击header时的getitem出现-1的情况.
    if (position < mListview.getHeaderViewsCount()) return;
    PlanManage content = mAdapter.getItem(position - 2);
    Intent i = new Intent(getActivity(), PlanManagePagerActivity.class);
    i.putExtra(PlanManageDetailFragment.EXTRA_VALUE, content);
    startActivityForResult(i, REQUEST_ADD);
  }

  @Override public void onRefresh(PullToRefreshBase<ListView> refreshView) {
    if (PullToRefreshBase.Mode.PULL_FROM_START == refreshView.getCurrentMode()) {
      mPage = 1;
    }
    if (PullToRefreshBase.Mode.PULL_FROM_END == refreshView.getCurrentMode()) {
      mPage++;
    }
    volleyPost();
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) {
      return;
    }
    if (requestCode == REQUEST_ADD) {
      mPullRefreshListView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
      mPage = 1;
      volleyPost();
      mPullRefreshListView.setMode(PullToRefreshBase.Mode.BOTH);
    }
    if (requestCode == REQUEST_QUERY) {
      ExtraValueContent content =
          (ExtraValueContent) data.getSerializableExtra(PlanManageQueryFragment.EXTRA_CONTENT);

      beginplanStartTime = content.getExtName1();
      endplanStartTime = content.getExtName2();
      excnameStr = content.getExtName3();
      excjobnoStr = content.getExtCode3();
      cornameStr = content.getExtName4();
      corjobnoStr = content.getExtCode4();
      mPullRefreshListView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
      mPage = 1;
      volleyPost();
      mPullRefreshListView.setMode(PullToRefreshBase.Mode.BOTH);
    }
  }

  @Override public void onClick(View view) {
    switch (view.getId()) {
      case R.id.ll_myMessage:
        //@我的
        Intent myMessage = new Intent(getActivity(), MyPlanProgressListActivity.class);
        myMessage.putExtra(MyPlanProgressListFragment.EXTRA_FROM,
            MyPlanProgressListFragment.EXTRA_MYMESSAGE);
        startActivity(myMessage);

        break;
      case R.id.ll_myPlan:
        //我@的
        Intent myPlan = new Intent(getActivity(), MyPlanProgressListActivity.class);
        myPlan.putExtra(MyPlanProgressListFragment.EXTRA_FROM,
            MyPlanProgressListFragment.EXTRA_MYPLAN);
        startActivity(myPlan);
        break;
      case R.id.ll_myReminder:
        //我的提醒
        Intent myRemind = new Intent(getActivity(), PlanMyRemindListActivity.class);
        startActivity(myRemind);
        break;
      default:
        break;
    }
  }
}
